import axios, { AxiosRequestConfig } from "axios";
import Taro, { RouterInfo } from "@tarojs/taro";
import { BASEURL_MAP } from "../constants";
import { delStore, getStore } from ".";
import { DecryptedJson } from "./encrypt-utils";
import stores from "../store";

export const instance = axios.create({
  baseURL: BASEURL_MAP.test,
});

export const getFromUrl = (
  router: RouterInfo<Partial<Record<string, string>>>
) => {
  let param = "";
  if (router.params) {
    Object.keys(router.params).forEach((k) => {
      param += `${k}=${router.params[k]}&`;
    });
    param = "?" + param;
  }
  if (!param) param = "?";
  param = `?from=${router?.path.replace(/\?.+/, "")}${encodeURIComponent(
    param
  )}`;
  return param;
};

instance.interceptors.request.use((config: AxiosRequestConfig) => {
  const token = getStore("token");
  if (token) {
    if (!config.headers) config.headers = {};
    config.headers.Authorization = token;
  }
  return config;
});
instance.interceptors.response.use((res: any) => {
  if (res.data && res.data.aes) {
    const result = DecryptedJson(
      res.data.aes,
      res.data.data,
      getStore("priRsaKey") || ""
    );
    return result;
  }
  return res;
});
instance.interceptors.response.use((res) => {
  if (res.data && res.data.code === 1) {
    if (res.data.code === 1) {
      delStore("token");
      stores.rootStore.getToken();
    }
    const { router } = Taro.getCurrentInstance();
    let param = getFromUrl(
      router as RouterInfo<Partial<Record<string, string>>>
    );
    Taro.navigateTo({
      // 需要区分项目、文件、确认项
      url: `/pages/project-login/index${param}`,
    });
    return res;
  }
  return res;
});
